<template>
    <div class="container">
        <el-row class="head" :gutter="20">
            <el-col class="flex" :md="24" :lg="11">
                <div class="title">设备管理</div>
                <div class="handle">
                    <el-button class="button" type="primary" @click="handleAddEquipment">
                        新增设备
                    </el-button>
                </div>
            </el-col>
        </el-row>
        <el-row class="main_device" :gutter="20">
            <el-col class="left-wrap" :md="24" :lg="11" style="position: relative">
                <el-table ref="mainTable" class="table" :data="equipments" highlight-current-row
                    :row-style="{ height: '60px' }" :header-row-style="{ height: '60px', backgroundColor: '#191e4b' }"
                    :header-cell-style="{ color: '#fff', backgroundColor: '#191e4b' }"
                    @current-change="handleCurrentChangeEquipment">
                    <el-table-column property="id" label="设备ID" min-width="70" align="center"></el-table-column>
                    <el-table-column property="title" label="设备名" min-width="90" align="center"></el-table-column>
                    <el-table-column property="brand" label="品牌" min-width="60" align="center"></el-table-column>
                    <el-table-column property="deviceType" label="设备类型" min-width="120" align="center">
                        <template #default="scope">
                            <span>{{ deviceTypeToString(scope.row.deviceType) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column property="module" label="模块" min-width="120" align="center">
                        <template #default="scope">
                            <span>{{ scope.row.module }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column property="count" label="功能个数" min-width="90" align="center">

                        <template #default="scope">
                            <span>{{ scope.row.count }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="150" align="center">
                        <template #default="scope">
                            <el-button class="button" size="small" type="text" @click.stop="handleEditEquipment(scope.row)">
                                修改
                            </el-button>
                            <el-button class="button" size="small" type="text"
                                @click.stop="handleDeleteEquipment(scope.row)">
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <!-- <vab-PagTable class="pagination-Box" :total="total" :page="queryForm.offset" :limit="queryForm.limit"
                    @changeSize="changeSize" @changePage="changePage"></vab-PagTable> -->
                <Pagination ref="paginationRef" @handleChange="handleChange" />

                <equipment-dialog ref="equipment_dialog" :device-type-list="deviceTypeList"
                    @change-equipment="changeEquipment"></equipment-dialog>
            </el-col>
            <el-col class="right-wrap" :md="24" :lg="13">
                <div class="tables">
                    <div v-if="isControlTypes" class="table1">
                        <el-table ref="controlTypeTable" class="table" :data="controlTypes" highlight-current-row border
                            :row-style="{ height: '60px' }" :header-row-style="{ height: '60px' }"
                            @current-change="handleCurrentChangeControlType">
                            <el-table-column property="label" label="控制类型" min-width="90" align="center">
                                <template #default="scope">
                                    <span>{{ scope.row.label }}</span>
                                    <el-button v-if="scope.row.label" class="button" size="small" type="text"
                                        @click.stop="handleDeleteControlType(scope.row)">
                                        删除
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <el-button v-if="isControlTypes" class="button circle-plus-button" size="medium"
                            icon="el-icon-circle-plus-outline" @click="handleAddControlType" :disabled="isDisStatu">
                            新增
                        </el-button>
                    </div>
                    <div class="table2">
                        <component :is="componentId" ref="mycomponent"></component>
                    </div>
                </div>
                <div v-if="isControlTypes" class="handle">
                    <el-button class="button" @click="handleReset">取消</el-button>
                    <el-button class="button" type="primary" @click="handleSubmit()">
                        确认
                    </el-button>
                </div>
                <control-type-dialog ref="control_type_dialog"
                    @change-control-type="changeControlType"></control-type-dialog>
            </el-col>
        </el-row>
        <el-row class="foot">
            <!-- <el-col class="handle" :span="12">
        <el-button class="button" @click="handleReset">取消</el-button>
        <el-button class="button" type="primary" @click="handleSubmit()">
          确认
        </el-button>
      </el-col> -->
        </el-row>
    </div>
</template>

<script>
/* 引入组件 */
import vabPagTable from './components/VabPagination/index.vue'
import EquipmentDialog from './components/equipmentDialog.vue'
import ControlTypeDialog from './components/controlTypeDialog.vue'
import Table1 from './components/table1.vue'
import Table2 from './components/table2.vue'
import Table3 from './components/table3.vue'
import Table4 from './components/table4.vue'
import Table5 from './components/table5.vue'
import Table6 from './components/table6.vue'
import Table7 from './components/table7.vue'
import Table8 from './components/table8.vue'
import Table9 from './components/table9.vue'
import Table10 from './components/table10.vue'
/* 引入接口 */
import EsAjax from '@/utils/EsAjax';
import ApiUrls from '@/apis/index';
import Pagination from '@/components/pagination/index.vue';

// 设备类型
const deviceTypeMap = {}
export default {
    name: 'EquipmentManagement',
    components: {
        Pagination,
        vabPagTable,
        EquipmentDialog,
        ControlTypeDialog,
        Table1,
        Table2,
        Table3,
        Table4,
        Table5,
        Table6,
        Table7,
        Table8,
        Table9,
        Table10,

    },
    filters: {
        deviceTypeFilter(type) {
            return deviceTypeMap[type]
        },
    },
    props: {},
    data() {
        return {
            queryForm: {
                query: '',
                sort: 'Id',
                order: 'desc',
                offset: 1,
                limit: 10,
            },
            paginationRef: null,
            equipments: [], // 设备列表
            // total: 0,
            equipment: {}, // 单个设备
            controlMode: [], // 单个设备控制方式
            actions: [], // 单个设备功能
            deviceTypeList: [], // 设备类型（过滤回显）
            isControlTypes: false, // 是否显示控制方式
            controlTypes: [], // 控制方式列表(页面显示)
            componentId: '', // is 组件切换名称
            moduleList: [], // 模块列表
            controlTypeList: [], // 控制方法列表
            isDisStatu: false,//新增控制类型是否禁用
            //controlTypeAdded: false, // 添加一个标志变量来表示是否已添加控制类型
        }
    },
    created() { },
    mounted() {
        this.init() // 初始化数据
    },
    methods: {
        /* 初始化数据 */
        init() {
            this.moduleList = [
                { id: '1', value: '001', label: 'ControlledDev' },
                { id: '2', value: '002', label: 'TPS' },
                { id: '3', value: '003', label: 'TouchPanel' },
                { id: '4', value: '004', label: 'BGServer' },
                { id: '5', value: '005', label: 'Sensor61' },
                { id: '6', value: '006', label: 'Oscillator' },
                { id: '7', value: '007', label: 'Timer' },
            ]
            this.controlTypeList = [ //控制类型列表
                { id: '1', value: 'rs232', label: 'RS-232' },
                { id: '2', value: 'rs485', label: 'RS-485' },
                { id: '3', value: 'tcp', label: 'TCP' },
                { id: '4', value: 'crestronnet', label: 'Crestronnet' },
                { id: '5', value: 'bgserver', label: 'BGServer' },
                { id: '6', value: 'relay', label: 'Relay' },
                { id: '7', value: 'time', label: 'Time' },
                { id: '8', value: 'IO', label: 'IO' },
                { id: '9', value: 'udp-recv', label: 'udp-recv' },
                { id: '10', value: 'udp-send', label: 'udp-send' },
            ]
            this.getEquipmentTypeList() // 所有的设备类型
            this.loadData() // 设备列表
        },
        // 获取设备列表
        // getDeviceList() {
        //   let params = JSON.parse(JSON.stringify(this.queryForm))
        //   params.offset = this.queryForm.offset - 1
        //   // let res = await getDeviceList(params)
        //   // if (res.code === 200) {
        //   //   this.equipments = res.data.list
        //   //   this.total = res.data.totalCount
        //   // }
        //   EsAjax.post(ApiUrls.equipmentDatagrid, params).then(res => {
        //     if (res.data.code === 200) {
        //       this.equipments = res.data.data.list
        //       this.total = res.data.data.totalCount
        //     }
        //   })
        // },
        loadData() {
            this.queryForm.offset = (this.queryForm.page - 1) || 0;
            EsAjax.post(ApiUrls.equipmentTypeList, { ...this.queryForm }).then(res => {
                if (res.data.code != 200) {
                    this.$message.error(res.msg)
                    return;
                }
                let { list, totalCount } = res.data.data
                list.map((equipment) => {
                    // 解析 actions 字段，转换为数组
                    if (equipment.actions) {
                        const actionsArray = JSON.parse(equipment.actions)
                        console.log(actionsArray);
                        // 计算 actions 数量
                        const actionsCount = actionsArray.length;
                        // 在当前数据中增加一个字段 count 存储 actions 数量
                        equipment.count = actionsCount;
                    } else {
                        equipment.count = 0;
                    }

                    return equipment; // 返回更新后的对象
                });
                this.equipments = list;
                console.log(this.$refs.paginationRef, 'total');
                this.$refs.paginationRef?.changeTotal({ totalCount: totalCount })
            }).catch(err => {
                this.$message.success(err.msg)
                console.log(err);
            }).finally(() => {
            })

        },
        // 左侧教室列表 分页
        changeSize(data) {
            this.queryForm.limit = data
            this.getDeviceList() // 设备列表
        },
        changePage(data) {
            this.queryForm.offset = data
            this.getDeviceList() // 设备列表
        },
        // 所有的设备类型数据
        getEquipmentTypeList() {
            let params = {
            }
            // let res = await getEquipmentTypeList(params)
            // if (res.code === 200 && res.data) {
            //   this.deviceTypeList = res.data.map((item) => {
            //     let key = item.type
            //     deviceTypeMap[key] = item.name
            //     let obj = {
            //       id: item.id,
            //       value: item.type,
            //       label: item.name,
            //       module: item.module,
            //       disabled: Number(item.isDelete) === 1 ? true : false,
            //     }
            //     return obj
            //   })
            // }
            EsAjax.post(ApiUrls.sleEquipmentTypeList, params).then(res => {
                if (res.data.code === 200 && res.data.data) {
                    this.deviceTypeList = res.data.data.map((item) => {
                        let key = item.type
                        deviceTypeMap[key] = item.name
                        let obj = {
                            id: item.id,
                            value: item.type,
                            label: item.name,
                            module: item.module,
                            disabled: Number(item.isDelete) === 1 ? true : false,
                        }
                        return obj
                    })
                    console.log(this.deviceTypeList);
                }
            })
        },
        // 类型转字符串
        deviceTypeToString(type) {
            return this.deviceTypeList.filter(v => { return v.value === type })[0]?.label

        },
        // 处理分页尺寸
        handleChange(data = null) {
            console.log(data);
            this.queryForm.page = data?.page;
            this.queryForm.limit = data?.limit;
            this.loadData();
        },
        /* 左侧设备表格 */
        // 新增设备
        handleAddEquipment() {
            let title = '新增设备'
            let data = {}
            this.$refs.equipment_dialog.show(title, data)
        },
        // 修改设备
        handleEditEquipment(row) {
            let title = '修改设备'
            this.$refs.equipment_dialog.show(title, row)
        },
        // 接收对话框的传值,添加|修改设备列表
        changeEquipment(data) {
            let params = data
            // let res = await editDevice(params)
            EsAjax.post(ApiUrls.k5deviceEdit, params).then(res => {
                if (res.data.code === 200) {
                    this.$message.success('成功！')
                    this.loadData()
                }
            })

        },
        // 删除设备
        handleDeleteEquipment(row) {
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    let ids = []
                    ids.push(row.id)
                    let params = {
                        ids: ids.toString(),
                    }
                    EsAjax.post(ApiUrls.k5deviceDel, params).then(res => {
                        if (res.data.code === 200) {
                            this.loadData() // 设备列表
                            this.$message.success(res.msg)
                        } else {
                            this.$message.error(res.msg)
                        }
                    })
                })
                .catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除',
                    })
                })
        },
        /**
         * 选中当行设备数据
         * element Table 中 current-change 方法进行表格当行选中
         * 数据更新时回取消选中项，同样会触发 current-change 方法但不会传值
         * 通过 current-change 方法的传值判断当前情况从而进行后续操作（是否打开后续内容）
         */
        handleCurrentChangeEquipment(value) {
            this.removeSession() // 清除数据缓存
            if (value) {
                this.equipment = JSON.parse(JSON.stringify(value)) // 获取选中列表
                console.log(this.equipment, 'fff'); //
                let controlAddType = this.equipment.controlType
                console.log(!controlAddType);
                if (!controlAddType) {
                    this.isDisStatu = false
                } else {
                    this.isDisStatu = true
                }
                this.controlMode = this.equipment.config
                    ? JSON.parse(this.equipment.config)
                    : [] // 控制回显
                this.actions = this.equipment.actions
                    ? JSON.parse(this.equipment.actions)
                    : [] // 功能回显
                this.controlTypeList.forEach((element) => {
                    let isType = this.equipment.controlType.includes(element.value)
                    if (isType) {
                        this.controlTypes.push(element)
                    }
                })
                // 必须加上 $nextTick，否则控制类型列表中选中项不变
                this.$nextTick(() => {
                    this.isControlTypes = true // 打开控制类型列表
                })
                // this.getEquipmentActions() // 获取设备功能
            } else {
                this.isControlTypes = false // 打开控制类型列表
            }
        },
        // 获取设备功能
        getEquipmentActions() {
            let params = {
                equipmentType: this.equipment.deviceType,
            }
            // let res = await getEquipmentActions(params)
            EsAjax.post(ApiUrls.equipmentActions, params).then(res => {
                console.log(res);
            })
        },
        /* 中间选项 */
        // 新增控制类型
        handleAddControlType() {
            this.$refs.control_type_dialog.show(this.equipment.controlType)
            //this.controlTypeAdded = true; // 设置标志变量为 true，表示已添加控制类型
        },
        // 接收对话框的传值
        changeControlType(data) {
            console.log(this.equipment.controlType)
            let types = this.equipment.controlType
                ? this.equipment.controlType.split(',')
                : [] // 已存在控制类型
            this.controlTypeList.forEach((element) => {
                // 先判断是否存在该值
                let isNewType = data.types.includes(element.value) // 判断新增数据
                let isOldType = types.includes(element.value) // 判断回显数据
                // 新增数据存在并且回显数据不存在时添加新的值
                if (isNewType && !isOldType) {
                    types.push(element.value) // 添加控制类型
                    this.controlTypes.push(element) // 添加控制类型按钮
                    let obj = {
                        communicationId: element.id,
                        communication: element.label,
                    }
                    this.controlMode.push(obj) // 添加新的控制方法
                }
            })
            this.equipment.controlType = types.toString() // 单个设备-控制类型
            this.equipment.config = JSON.stringify(this.controlMode) // 单个设备-控制类型详情
            // this.changeEquipment(this.equipment) // 更新控制类型
        },

        // 删除控制类型
        handleDeleteControlType(row) {
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                // 页面目录
                let controlTypes = this.controlTypes.filter(
                    (item) => item.value !== row.value
                )
                // 后端参数
                let types = controlTypes.map((item) => item.value)
                console.log('1-1', this.controlMode)
                let controlMode = this.controlMode.filter(
                    (item) => item.communicationId !== row.id
                )
                console.log('1-2', controlMode)

                console.log('2-1', this.actions)
                let actions = this.actions.filter(
                    (item) => item.communicationId !== row.id
                )
                console.log('2-2', actions)
                // this.$message.success('删除成功!')

                this.$nextTick(() => {
                    this.componentId = ''
                    sessionStorage.removeItem('T00' + row.id)
                    this.controlTypes = controlTypes // 页面展示
                    this.controlMode = controlMode
                    this.actions = actions
                    this.equipment.controlType = types.toString() // 单个设备-控制类型
                    this.equipment.config = JSON.stringify(controlMode) // 单个设备-控制类型详情
                    this.equipment.actions = JSON.stringify(actions) // 单个设备
                    this.changeEquipment(this.equipment) // 更新控制类型
                    this.removeSession() // 清除数据缓存
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除',
                })
            })
        },
        // 选中当行设备数据
        handleCurrentChangeControlType(value) {
            const that = this
            if (value) {
                this.componentId = value.id ? 'Table' + value.id : ''
                this.$nextTick(() => {
                    that.$refs.mycomponent.show(
                        value.id,
                        this.equipment,
                        that.equipment.module
                    )
                })
            }
        },
        /* 整页操作 */
        // 取消操作
        handleReset() {
            this.removeSession() // 清空数据
        },
        // 确认提交
        handleSubmit() {
            if (Object.keys(this.equipment).length <= 2) {
                return
            }
            // 获取设备本身的信息(深拷贝)
            let cArr = JSON.parse(JSON.stringify(this.controlMode)) || []
            console.log(this.actions);
            if (this.actions) {
                var aAarr = JSON.parse(JSON.stringify(this.actions))
            } else {
                var aAarr = []

            }

            // 获取组件传递过来的值
            let device = { controlMode: {}, actions: [] } // 默认数据
            let T001 = JSON.parse(sessionStorage.getItem('T001')) || device
            let T002 = JSON.parse(sessionStorage.getItem('T002')) || device
            let T003 = JSON.parse(sessionStorage.getItem('T003')) || device
            let T004 = JSON.parse(sessionStorage.getItem('T004')) || device
            let T005 = JSON.parse(sessionStorage.getItem('T005')) || device
            let T006 = JSON.parse(sessionStorage.getItem('T006')) || device
            let T007 = JSON.parse(sessionStorage.getItem('T007')) || device
            let T008 = JSON.parse(sessionStorage.getItem('T008')) || device
            let T009 = JSON.parse(sessionStorage.getItem('T009')) || device
            let T010 = JSON.parse(sessionStorage.getItem('T010')) || device
            console.log('1-3', this.controlMode)
            // 循环遍历获取设备控制方式设置
            this.controlMode = cArr.map((item) => {
                if (item.communicationId == T001.cid) {
                    return T001.controlMode
                } else if (item.communicationId == T002.cid) {
                    return T002.controlMode
                } else if (item.communicationId == T003.cid) {
                    return T003.controlMode
                } else if (item.communicationId == T004.cid) {
                    return T004.controlMode
                } else if (item.communicationId == T005.cid) {
                    return T005.controlMode
                } else if (item.communicationId == T006.cid) {
                    return T006.controlMode
                } else if (item.communicationId == T007.cid) {
                    return T007.controlMode
                } else if (item.communicationId == T008.cid) {
                    return T008.controlMode
                } else if (item.communicationId == T009.cid) {
                    return T009.controlMode
                } else if (item.communicationId == T010.cid) {
                    return T010.controlMode
                } else {
                    return item
                }
            })
            console.log('总结控制数据', this.controlMode)
            this.equipment.config = JSON.stringify(this.controlMode) // 单个设备

            let ids = [T001.cid, T002.cid, T003.cid, T004.cid, T005.cid, T006.cid, T007.cid, T008.cid, T009.cid, T010.cid]
            // 去除原功能组中已编辑的内容
            console.log(aAarr);
            let updateArr = aAarr.filter((item) => {
                let flag = ids.filter(Boolean).includes(item.communicationId) // 判断是否含有改ID
                return !flag
            })
            // 解构并合并，获取所有编辑的功能组
            let newArr = [
                ...updateArr,
                ...T001.actions,
                ...T002.actions,
                ...T003.actions,
                ...T004.actions,
                ...T005.actions,
                ...T006.actions,
                ...T007.actions,
                ...T008.actions,
                ...T009.actions,
                ...T010.actions,
            ]
            console.log(newArr, '新数组')
            // 数组去重
            this.actions = newArr.filter((item, index) => {
                let i = newArr.findIndex((ele) => {
                    let flag_c = ele.communicationId === item.communicationId
                    let flag_a = ele.action === item.action
                    return flag_c && flag_a
                })
                return i === index
            })
            console.log('总结功能数据', this.actions)
            this.equipment.actions = JSON.stringify(this.actions)// 单个设备
            this.changeEquipment(this.equipment) // 更新设备列表
            this.removeSession() // 清空数据
        },
        // 清空数据
        removeSession() {
            this.actions = [] // 清空当前功能参数
            this.controlMode = [] // 清空当前控制类型
            this.controlTypes = [] // 清空当前按钮列表
            this.equipment = {} // 当前选中设备数据
            this.isControlTypes = false // 关闭按钮列表
            this.componentId = '' // 关闭控制与功能参数
            // 清空本地Session
            sessionStorage.removeItem('T001')
            sessionStorage.removeItem('T002')
            sessionStorage.removeItem('T003')
            sessionStorage.removeItem('T004')
            sessionStorage.removeItem('T005')
            sessionStorage.removeItem('T006')
            sessionStorage.removeItem('T007')
            sessionStorage.removeItem('T008')
            sessionStorage.removeItem('T009')
            sessionStorage.removeItem('T010')
        },
    },
}
</script>
<style lang="scss" scoped>
/* 组件样式 */
.el-row {
    margin-bottom: 20px;

    .el-col {
        border-radius: 4px;
    }

    &:last-child {
        margin-bottom: 0;
    }
}

.container {
    padding: 10px 16px;

    .head {
        padding-top: 3px;

        .flex {
            height: 40px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .title {
            color: #666;
            font-size: 14px;
            line-height: 1.5;
        }

        .handle {
            text-align: right;
        }
    }

    .main_device {
        min-height: 500px;

        .table {
            width: 100%;
            margin-bottom: 20px;
        }

        .tables {
            display: flex;
            justify-content: center;
            align-items: flex-start;

            .button {
                margin: 0 5px;
            }

            .circle-plus-button {
                width: 100%;
                font-size: 16px;
                line-height: 1.5;
                border-color: transparent;
                margin: 0;
            }

            .table1 {
                width: 175px;
                min-width: 175px;
                max-width: 175px;
            }

            .table2 {
                flex: 1;
                max-width: calc(100% - 175px);
                min-height: 745px;
                max-height: 2000px;
            }
        }

        .handle {
            width: 100%;
            text-align: center;
        }
    }

    .foot .handle {
        text-align: right;
    }
}

::v-deep .el-table__body tr.current-row>td.el-table__cell {
    background-color: #46a5ff;

    .cell,
    .button {
        color: #ffffff;
    }
}
</style>
